/**
 * 
 */
package neptune.web.client.controller;

import com.google.gwt.user.client.rpc.AsyncCallback;

import neptune.web.client.services.experiment.ExperimentService;
import neptune.web.client.view.ConsoleManager;
import neptune.web.client.view.ExperimentView;
import neptune.web.client.view.OperativeView;
import neptune.web.client.view.SuperView;
import neptune.web.client.view.ViewManager;
import neptune.web.client.view.components.UserTable;
import neptune.web.client.view.components.dialogs.PropertiesDialog;
import neptune.web.client.view.components.dialogs.PropertiesDialogListener;

/**
 * @author Roberto Bifulco [info@robertobifulco.it, robertobifulco.it]
 * 
 */
public class AddUserToExperimentController implements PropertiesDialogListener {

	private boolean isSuperUser;
	private String expId;

	/**
	 * 
	 * @param isSuperUser
	 * @param expId
	 */
	public AddUserToExperimentController(boolean isSuperUser, String expId) {
		this.isSuperUser = isSuperUser;
		this.expId = expId;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see neptune.web.client.view.components.dialogs.PropertiesDialogListener#okPressed(java.lang.String[][],
	 *      neptune.web.client.view.components.dialogs.PropertiesDialog)
	 */
	public void okPressed(String[][] properties, final PropertiesDialog sender) {
		final String username = properties[0][1];
		ExperimentService.Util.getInstance().addUserToExperiment(username,
				expId, isSuperUser, new AsyncCallback<Boolean>() {

					public void onSuccess(Boolean arg0) {
						String message = "User '" + username
								+ "' successfully added to experiment '"
								+ expId + "'";
						ConsoleManager.addConsoleMessage(message, false);
						sender.showMessage(message);

						SuperView operative = (SuperView) ViewManager
								.getViewManager().getViewByName(
										OperativeView.DEFAULT_TOKEN);
						ExperimentView view = (ExperimentView) operative
								.getViewByName(ExperimentView.DEFAULT_TOKEN);
						
						UserTable table;
//						if(isSuperUser);
////							table = view.getSuperUserTable();TODO
//						else
							table = view.getUserTable();
						
						table.addUsername(username);
					}

					public void onFailure(Throwable arg0) {
						String message = "Unable to add user '" + username
								+ "' to experiment '" + expId + "'. Cause: "
								+ arg0.getMessage();
						ConsoleManager.addConsoleMessage(message, true);
						sender.showMessage(message);
					}

				});
	}

}
